package com.galen.manual.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.galen.manual.common.Result;
import com.galen.manual.context.UserContextHolder;
import com.galen.manual.dto.UserManageQueryDTO;
import com.galen.manual.dto.UserStatusUpdateDTO;
import com.galen.manual.entity.User;
import com.galen.manual.mapper.UserMapper;
import com.galen.manual.annotation.RequireAdminRole;
import com.galen.manual.vo.UserManageVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理员控制器 - 用户管理功能
 */
@Slf4j
@Tag(name = "管理员功能", description = "管理员专用接口")
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final UserMapper userMapper;

    @Operation(summary = "管理员健康检查", description = "检查管理员服务是否正常")
    @GetMapping("/health")
    public Result<String> health() {
        log.info("管理员服务健康检查");
        return Result.success("管理员服务正常");
    }

    @Operation(summary = "获取当前管理员信息", description = "获取当前登录管理员的信息")
    @GetMapping("/profile")
    public Result<String> getAdminProfile() {
        log.info("获取管理员信息");
        return Result.success("管理员信息获取成功");
    }

    // ================== 用户管理接口 ==================

    @Operation(summary = "获取用户列表", description = "超级管理员查询用户列表，支持分页和筛选")
    @RequireAdminRole(message = "只有超级管理员可以查看用户列表")
    @GetMapping("/users")
    public Result<Page<UserManageVO>> getUserList(@Valid UserManageQueryDTO queryDTO) {
        log.info("获取用户列表，关键词: {}, 状态: {}, 等级: {}, 排除管理员: {}",
                queryDTO.getKeyword(), queryDTO.getStatus(), queryDTO.getUserLevel(), queryDTO.getExcludeAdmins());

  
        // 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 关键词搜索（用户名、昵称、手机号）
        if (queryDTO.getKeyword() != null && !queryDTO.getKeyword().trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("username", queryDTO.getKeyword())
                .or()
                .like("nickname", queryDTO.getKeyword())
                .or()
                .like("phone", queryDTO.getKeyword())
            );
        }

        // 状态筛选
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq("status", queryDTO.getStatus());
        }

        // 用户等级筛选
        if (queryDTO.getUserLevel() != null) {
            queryWrapper.eq("user_level", queryDTO.getUserLevel());
        }

        // 时间范围筛选
        if (queryDTO.getStartTime() != null && !queryDTO.getStartTime().trim().isEmpty()) {
            try {
                LocalDateTime startTime = LocalDateTime.parse(queryDTO.getStartTime() + " 00:00:00",
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                queryWrapper.ge("create_time", startTime);
            } catch (Exception e) {
                log.warn("开始时间格式错误: {}", queryDTO.getStartTime());
            }
        }

        if (queryDTO.getEndTime() != null && !queryDTO.getEndTime().trim().isEmpty()) {
            try {
                LocalDateTime endTime = LocalDateTime.parse(queryDTO.getEndTime() + " 23:59:59",
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                queryWrapper.le("create_time", endTime);
            } catch (Exception e) {
                log.warn("结束时间格式错误: {}", queryDTO.getEndTime());
            }
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");

        // 分页查询
        Page<User> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);

        // 转换为VO并过滤管理员（如果需要）
        Page<UserManageVO> voPage = new Page<>();
        BeanUtils.copyProperties(userPage, voPage);

        List<UserManageVO> voList = new ArrayList<>();
        for (User user : userPage.getRecords()) {
            // 如果需要排除管理员，检查是否为管理员
            if (queryDTO.getExcludeAdmins() && user.getIsAdmin() != null && user.getIsAdmin()) {
                continue;
            }
            voList.add(convertToUserManageVO(user));
        }

        voPage.setRecords(voList);
        voPage.setTotal(voList.size()); // 重新计算总数

        return Result.success(voPage);
    }

    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    @RequireAdminRole(message = "只有超级管理员可以查看用户详情")
    @GetMapping("/users/{userId}")
    public Result<UserManageVO> getUserDetail(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
        log.info("获取用户详情，用户ID: {}", userId);

        User user = userMapper.selectUserWithAdminInfo(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        return Result.success(convertToUserManageVO(user));
    }

    @Operation(summary = "更新用户状态", description = "冻结、解冻或拉黑用户")
    @RequireAdminRole(message = "只有超级管理员可以修改用户状态")
    @PutMapping("/users/status")
    public Result<String> updateUserStatus(@Valid @RequestBody UserStatusUpdateDTO updateDTO) {
        log.info("更新用户状态，用户ID: {}, 新状态: {}, 原因: {}",
                updateDTO.getUserId(), updateDTO.getStatus(), updateDTO.getReason());

        // 验证状态值
        if (updateDTO.getStatus() < 0 || updateDTO.getStatus() > 3) {
            return Result.error("无效的状态值");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(updateDTO.getUserId());
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 防止修改超级管理员状态
        if (user.getIsAdmin() != null && user.getIsAdmin() && "super".equals(user.getAdminRole())) {
            return Result.error("不能修改超级管理员的状态");
        }

        // 更新用户状态
        int result = userMapper.updateUserStatus(updateDTO.getUserId(), updateDTO.getStatus());
        if (result > 0) {
            String statusText = getStatusText(updateDTO.getStatus());
            log.info("用户状态更新成功，用户ID: {}, 状态: {}, 操作管理员: {}",
                    updateDTO.getUserId(), statusText, UserContextHolder.getUserContext().getUsername());
            return Result.success("用户状态更新成功");
        } else {
            return Result.error("用户状态更新失败");
        }
    }

    @Operation(summary = "冻结用户", description = "冻结指定用户")
    @RequireAdminRole(message = "只有超级管理员可以冻结用户")
    @PutMapping("/users/{userId}/freeze")
    public Result<String> freezeUser(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId,
            @Parameter(description = "冻结原因") @RequestParam(required = false) String reason) {
        log.info("冻结用户，用户ID: {}, 原因: {}", userId, reason);

        UserStatusUpdateDTO updateDTO = new UserStatusUpdateDTO();
        updateDTO.setUserId(userId);
        updateDTO.setStatus(2); // 冻结状态
        updateDTO.setReason(reason);

        return updateUserStatus(updateDTO);
    }

    @Operation(summary = "解冻用户", description = "解冻指定用户")
    @RequireAdminRole(message = "只有超级管理员可以解冻用户")
    @PutMapping("/users/{userId}/unfreeze")
    public Result<String> unfreezeUser(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
        log.info("解冻用户，用户ID: {}", userId);

        UserStatusUpdateDTO updateDTO = new UserStatusUpdateDTO();
        updateDTO.setUserId(userId);
        updateDTO.setStatus(1); // 正常状态
        updateDTO.setReason("管理员解冻");

        return updateUserStatus(updateDTO);
    }

    @Operation(summary = "拉黑用户", description = "将用户加入黑名单")
    @RequireAdminRole(message = "只有超级管理员可以拉黑用户")
    @PutMapping("/users/{userId}/blacklist")
    public Result<String> blacklistUser(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId,
            @Parameter(description = "拉黑原因") @RequestParam(required = false) String reason) {
        log.info("拉黑用户，用户ID: {}, 原因: {}", userId, reason);

        UserStatusUpdateDTO updateDTO = new UserStatusUpdateDTO();
        updateDTO.setUserId(userId);
        updateDTO.setStatus(3); // 黑名单状态
        updateDTO.setReason(reason);

        return updateUserStatus(updateDTO);
    }

    @Operation(summary = "获取用户统计信息", description = "获取用户数量统计")
    @RequireAdminRole(message = "只有超级管理员可以查看用户统计")
    @GetMapping("/users/statistics")
    public Result<Object> getUserStatistics() {
        log.info("获取用户统计信息");

        // 统计各状态用户数量（排除管理员）
        int normalCount = userMapper.countUsersByStatus(1, true);
        int frozenCount = userMapper.countUsersByStatus(2, true);
        int blacklistedCount = userMapper.countUsersByStatus(3, true);

        java.util.Map<String, Object> statistics = new java.util.HashMap<>();
        statistics.put("normalUserCount", normalCount);
        statistics.put("frozenUserCount", frozenCount);
        statistics.put("blacklistedUserCount", blacklistedCount);
        statistics.put("totalUserCount", normalCount + frozenCount + blacklistedCount);

        return Result.success(statistics);
    }

    // ================== 私有辅助方法 ==================

    /**
     * 转换为用户管理VO
     */
    private UserManageVO convertToUserManageVO(User user) {
        UserManageVO vo = new UserManageVO();
        BeanUtils.copyProperties(user, vo);

        // 设置状态名称和等级名称
        vo.setStatusName(vo.getStatusName());
        vo.setUserLevelName(vo.getUserLevelName());

        // 处理金额格式
        if (user.getTotalEarnings() != null) {
            vo.setTotalEarnings(BigDecimal.valueOf(user.getTotalEarnings()));
        }
        if (user.getBalance() != null) {
            vo.setBalance(BigDecimal.valueOf(user.getBalance()));
        }

        return vo;
    }

    /**
     * 获取状态文本
     */
    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "待审核";
            case 1: return "正常";
            case 2: return "冻结";
            case 3: return "黑名单";
            default: return "未知";
        }
    }

    /**
     * 获取客户端IP地址的简单实现
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}